#include "XmmsPlayer.h"
#include <dlfcn.h>
#include <iostream>

// ===========================================================================
// XMMS
// ==========================================================================
CXmmsPlayer::CXmmsPlayer()
{
    xmms_remote_get_playlist_title = 0;
    xmms_remote_get_playlist_pos = 0;
    xmms_remote_get_output_time = 0;
    xmms_remote_is_paused = 0;
    xmms_remote_is_playing = 0;

    handle = 0;
    m_isOK = false;

    Init();
}

CXmmsPlayer::~CXmmsPlayer()
{
    if( handle )
    {
        dlclose(handle);
    }
}

bool CXmmsPlayer::Init()
{
    handle = dlopen("libxmms.so", RTLD_NOW);

    if( handle )
    {
        xmms_remote_is_playing = (bool (*)(int))dlsym(handle, "xmms_remote_is_playing");
        xmms_remote_is_paused = (bool (*)(int))dlsym(handle, "xmms_remote_is_paused");
        xmms_remote_get_output_time = (int (*)(int))dlsym(handle, "xmms_remote_get_output_time");
        xmms_remote_get_playlist_pos = (int (*)(int))dlsym(handle, "xmms_remote_get_playlist_pos");
        xmms_remote_get_playlist_title = (char*(*)(int,int))dlsym(handle, "xmms_remote_get_playlist_title");
    }
    
    m_isOK = xmms_remote_get_playlist_title && 
        xmms_remote_get_playlist_pos && 
        xmms_remote_get_output_time && 
        xmms_remote_is_paused &&
        xmms_remote_is_playing;

    return m_isOK;
}

bool CXmmsPlayer::IsOpen()
{
    if( m_isOK )
    {
        return xmms_remote_is_playing(0) || xmms_remote_is_paused(0);
    }
    return false;
}

std::string CXmmsPlayer::GetMediaTitle()
{
    if( !IsOpen() )
    {
        return "";
    }

    int pos = xmms_remote_get_playlist_pos(0);
    return xmms_remote_get_playlist_title(0, pos);
}

int CXmmsPlayer::GetCurrentTime()
{
    if( !IsOpen() )
    {
        return -1;
    }

    return xmms_remote_get_output_time(0);
}


